package com.softtown.modules.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.softtown.common.annotation.LogOperation;
import com.softtown.common.enums.MsgSendWayTypeEnum;
import com.softtown.common.enums.MsgTypeEnum;
import com.softtown.common.enums.SysMessageIsReadEnum;
import com.softtown.common.exception.ErrorCode;
import com.softtown.common.exception.RenException;
import com.softtown.common.regularUtils.RegularUtils;
import com.softtown.common.utils.Result;
import com.softtown.common.validator.ValidatorUtils;
import com.softtown.common.validator.group.AddGroup;
import com.softtown.common.validator.group.DefaultGroup;

import com.softtown.modules.message.service.SysEmailService;
import com.softtown.modules.message.sms.AbstractSmsService;
import com.softtown.modules.message.sms.SmsFactory;
import com.softtown.modules.sys.dto.AppealDTO;
import com.softtown.modules.sys.dto.SysCompDTO;

import com.softtown.modules.sys.entity.*;
import com.softtown.modules.sys.service.*;
import com.softtown.modules.sys.vo.SysCompanyVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;

import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

/**
 * 系统公司接口模块
 *
 * @author Dingyayong
 * @create 2019-05-20 15:44
 **/
@RestController
@RequestMapping("/sys/company")
@Api(tags = "公司管理")
public class SysCompanyController {

    @Resource
    private SysCompService sysCompService;

    @Resource
    private SysMsgSendWayService sysMsgSendWayService;

    @Resource
    private SysMessageService sysMessageService;

    @Resource
    private SysParamsService sysParamsService;

    @Resource
    private SysEmailService sysEmailService;

    @Resource
    private SysUserService sysUserService;

    @PostMapping("getList")
    @ApiOperation("获取公司信息列表")
    @LogOperation("获取公司信息列表")
    public Result<List<SysCompDTO>> list() {
        List<SysCompDTO> list = sysCompService.getListByIds();
        return new Result<List<SysCompDTO>>().ok(list);
    }

    /**
     * @param @param [compDTO]
     * @return @return com.softtown.common.utils.Result
     * @throws
     * @Title: register
     * @Description: 用户注册公司
     * @author fuming
     * @date 2019/5/31 17:17
     */
    @PostMapping("register")
    @ApiOperation("注册公司")
    @LogOperation("注册公司")
    public Result register(@RequestBody SysCompDTO compDTO) {
        Result result = new Result<>();
        //效验数据
        ValidatorUtils.validateEntity(compDTO, AddGroup.class, DefaultGroup.class);
        if (RegularUtils.isCompName(compDTO.getName())) {
            return result.error(ErrorCode.COMPANY_NAME_TYPE);
        }
        if (!RegularUtils.isuscc(compDTO.getUscc())) {
            return result.error(ErrorCode.INCORRECT_USCC_FORMAT);
        }
        if (!compDTO.getTel().isEmpty()) {
            if (!RegularUtils.istel(compDTO.getTel())) {
                return result.error(ErrorCode.INCORRECT_TELEPHONE_FORMAT);
            }
        }
        if (!RegularUtils.isMobile(compDTO.getMobile())) {
            return result.error(ErrorCode.INCORRECT_MOBILE_FORMAT);
        }
        if (RegularUtils.isName(compDTO.getName())) {
            return result.error(ErrorCode.INCORRECT_NAME_FORMAT);
        }
        SysCompEntity compInfo = sysCompService.getCompInfo(compDTO.getName());
        SysCompEntity sysCompEntity = sysCompService.getCompanyByUscc(compDTO.getUscc());
        SysCompEntity sysCompEntity1 =
                sysCompService.getOne(new QueryWrapper<SysCompEntity>().lambda().eq(SysCompEntity::getAddress,
                        compDTO.getAddress()).eq(SysCompEntity::getIsDeleted, 0));
        if (compInfo != null) {
            return result.error(ErrorCode.COMPANY_EXISTS);
        } else if (sysCompEntity != null) {
            return result.error(ErrorCode.USCC_EXISTS);
        } else {
            sysCompService.register(compDTO);
            return result;
        }
    }

    /**
     * @param @param [compDTO]
     * @return @return com.softtown.common.utils.Result
     * @throws
     * @Title: update
     * @Description: 公司信息修改
     * @author fuming
     * @date 2019/6/1 17:49
     */
    @PostMapping("updateCompInfo")
    @ApiOperation("公司信息修改")
    @LogOperation("公司信息修改")
    public Result update(@RequestBody SysCompDTO compDTO) {
        Result result = new Result<>();
        //效验数据
        ValidatorUtils.validateEntity(compDTO, DefaultGroup.class);
        SysCompanyVO companyInfo = sysCompService.getCompanyInfo(compDTO.getId());
        if (RegularUtils.isCompName(compDTO.getName())) {
            return result.error(ErrorCode.COMPANY_NAME_TYPE);
        } else {
            SysCompEntity sysCompEntity1 = sysCompService.getCompanyByCampanyName(compDTO.getName());
            if (sysCompEntity1 != null && !sysCompEntity1.getId().equals(companyInfo.getId())) {
                return result.error(ErrorCode.COMPANY_EXISTS);
            }
        }
        if (!RegularUtils.isuscc(compDTO.getUscc())) {
            return result.error(ErrorCode.INCORRECT_USCC_FORMAT);
        } else {
            SysCompEntity sysCompEntity = sysCompService.getCompanyByUscc(compDTO.getUscc());
            if (sysCompEntity != null && !sysCompEntity.getId().equals(companyInfo.getId())) {
                return result.error(ErrorCode.COMPANY_EXISTS);
            }
        }
        if (!"".equals(compDTO.getTel())) {
            if (!RegularUtils.istel(compDTO.getTel())) {
                return result.error(ErrorCode.INCORRECT_TELEPHONE_FORMAT);
            }
        }
        if (!RegularUtils.isMobile(compDTO.getMobile())) {
            return result.error(ErrorCode.INCORRECT_MOBILE_FORMAT);
        }
        if (RegularUtils.isName(compDTO.getContact())) {
            return result.error(ErrorCode.INCORRECT_NAME_FORMAT);
        }
        sysCompService.updateCompInfo(compDTO);
        return result;
    }

    /**
     * @param @param [compId]
     * @return @return com.softtown.common.utils.Result<com.softtown.modules.sys.vo.SysCompanyVO>
     * @throws
     * @Title: getCompanyInfo
     * @Description: 根据公司ID找出公司信息
     * @author fuming
     * @date 2019/6/28 9:27
     */
    @PostMapping("getCompanyInfoById")
    @ApiOperation("获取公司信息列表")
    @LogOperation("获取公司信息列表")
    public Result<SysCompanyVO> getCompanyInfo(@RequestBody String companyId) {
        String getCompanyId = JSONObject.fromObject(companyId).get("compId").toString();
        SysCompanyVO companyInfo = sysCompService.getCompanyInfo(Long.valueOf(getCompanyId));
        return new Result<SysCompanyVO>().ok(companyInfo);
    }

    /**
     * @param @param [userId]
     * @return @return com.softtown.common.utils.Result<java.util.List<com.softtown.modules.sys.vo.SysCompanyVO>>
     * @throws
     * @Title: getCompanyNameList
     * @Description: 根据用户ID查找公司ID和名称信息
     * @author fuming
     * @date 2019/7/1 21:37
     */
    @PostMapping("getCompanyNameByUserId")
    @ApiOperation("获取公司名称列表")
    @LogOperation("获取公司名称列表")
    public Result<List<SysCompanyVO>> getCompanyNameList(@RequestBody String userId) {
        String getUserId = JSONObject.fromObject(userId).get("userId").toString();
        List<SysCompanyVO> compNameListByUserId = sysCompService.getCompNameListByUserId(Long.valueOf(getUserId));
        return new Result<List<SysCompanyVO>>().ok(compNameListByUserId);
    }

    @PostMapping("appealToCompany")
    @ApiOperation(value = "向企业申诉")
    public Result appealToCompany(@RequestBody AppealDTO appealDTO) {
        Result result = new Result<>();
        String eamil = "MAIL_SERVICE_IS_USABLE";
        String sms = "SMS_SERVICE_IS_USABLE";
        String ok = "OK";
        String yes = "Y";
        String code = "Code";
        SysCompEntity compEntity = sysCompService.getCompInfo(appealDTO.getCompName().trim());
        if (compEntity != null) {
            SysMsgSendWayEntity sysMsgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                    STTATION_LETTER.value(), MsgTypeEnum.PASSWORD_REST_CODE.value());
            Object[] contentArray = new Object[]{appealDTO.getCompName(), appealDTO.getAcount(),
                    appealDTO.getCompMobile(), appealDTO.getCompEmail(), appealDTO.getCompMemo(),
                    appealDTO.getSelfMobile(), appealDTO.getSelfEmail()};
            String content = MessageFormat.format(sysMsgSendWayEntity.getMsgTemplateContent(), contentArray);
            SysMessageEntity sysMessageEntity = new SysMessageEntity();
            sysMessageEntity.setType(MsgTypeEnum.PASSWORD_REST_CODE.value());
            sysMessageEntity.setTitle(sysMsgSendWayEntity.getMsgTemplateTitle());
            sysMessageEntity.setContent(content);
            if (appealDTO.getAcount() != null) {
                SysUserEntity sysUserEntity = sysUserService.getUserByAccount(appealDTO.getAcount());
                if (sysUserEntity != null) {
                    sysMessageEntity.setSenderId(sysUserEntity.getId());
                    sysMessageEntity.setCreator(sysUserEntity.getId());
                    sysMessageEntity.setUpdateDate(new Date());
                    sysMessageEntity.setUpdater(sysUserEntity.getId());
                }
            } else {
                if (appealDTO.getCompEmail() != null) {
                    SysUserEntity sysUserEntity = sysUserService.getEntityByEmail(appealDTO.getCompEmail());
                    if (sysUserEntity != null) {
                        sysMessageEntity.setSenderId(sysUserEntity.getId());
                        sysMessageEntity.setUpdater(sysUserEntity.getId());
                        sysMessageEntity.setCreator(sysUserEntity.getId());
                        sysMessageEntity.setUpdateDate(new Date());
                    }
                } else {
                    SysUserEntity sysUserEntity = sysUserService.getEntityByMobile(appealDTO.getCompMobile());
                    if (sysUserEntity != null) {
                        sysMessageEntity.setCreator(sysUserEntity.getId());
                        sysMessageEntity.setUpdateDate(new Date());
                        sysMessageEntity.setSenderId(sysUserEntity.getId());
                        sysMessageEntity.setUpdater(sysUserEntity.getId());
                    }
                }
            }
            sysMessageEntity.setIsRead(SysMessageIsReadEnum.UNREAD.value());
            sysMessageEntity.setCreateDate(new Date());
            sysMessageEntity.setMsgSendWayType(MsgSendWayTypeEnum.
                    STTATION_LETTER.value());
            sysMessageEntity.setMsgCompId(compEntity.getId());
            sysMessageEntity.setReceiverId(compEntity.getAdminUserId());
            sysMessageEntity.setSendDate(new Date());
            sysMessageEntity.setUpdateTimestamp(String.valueOf(System.currentTimeMillis()));
            sysMessageService.insert(sysMessageEntity);
            String mail = sysParamsService.getValue(eamil);
            if (mail.equals(yes)) {
                SysUserEntity sysUserEntity = sysUserService.getByUserIdOnLoginOut(compEntity.getAdminUserId());
                if (sysUserEntity != null) {
                    if (sysUserEntity.getEmail() != null) {
                        boolean f = sysEmailService.sendEmailByAppeal(appealDTO, sysUserEntity.getEmail());
                        if (!f) {
                            return result.error(ErrorCode.EMAIL_FAIL_SEND);
                        }
                    } else {
                        return result.error(ErrorCode.EMAIL_FAIL_SEND);
                    }
                }
            }
            String sm = sysParamsService.getValue(sms);
            if (sm.equals(yes)) {
                SysMsgSendWayEntity msgSendWayEntity = sysMsgSendWayService.selectBySendTypeAndType(MsgSendWayTypeEnum.
                        SMS.value(), MsgTypeEnum.PASSWORD_REST_CODE.value());
                SysUserEntity sysUserEntity = sysUserService.getByUserIdOnLoginOut(compEntity.getAdminUserId());
                if (sysUserEntity != null) {
                    if (sysUserEntity.getMobile() != null) {
                        AbstractSmsService service = SmsFactory.build();
                        if (service == null) {
                            throw new RenException(ErrorCode.SMS_CONFIG);
                        }
                        if (appealDTO.getAcount() != null) {
                            String jsonString = service.sendSmsByLogin(sysUserEntity.getMobile(),
                                    msgSendWayEntity.getMsgTemplateCode(), appealDTO.getAcount());
                            if (JSONObject.fromObject(jsonString).isEmpty() || !ok.equals(JSONObject.fromObject(jsonString).get(code).toString())) {
                                return result.error(ErrorCode.SEND_SMS_ERROR);
                            }
                        } else {
                            if (appealDTO.getCompEmail() != null) {
                                String jsonString = service.sendSmsByLogin(sysUserEntity.getMobile(),
                                        msgSendWayEntity.getMsgTemplateCode(), appealDTO.getCompEmail());
                                if (JSONObject.fromObject(jsonString).isEmpty() || !ok.equals(JSONObject.fromObject(jsonString).get(code).toString())) {
                                    return result.error(ErrorCode.SEND_SMS_ERROR);
                                }
                            } else {
                                String jsonString = service.sendSmsByLogin(sysUserEntity.getMobile(),
                                        msgSendWayEntity.getMsgTemplateCode(), appealDTO.getCompMobile());
                                if (JSONObject.fromObject(jsonString).isEmpty() || !ok.equals(JSONObject.fromObject(jsonString).get(code).toString())) {
                                    return result.error(ErrorCode.SEND_SMS_ERROR);
                                }
                            }
                        }

                    }
                }
            }
        } else {
            return result.error(ErrorCode.COMPANY_NOT_EXISTS);
        }
        return result;
    }

    @PostMapping("getAdminUserName")
    @ApiOperation("获取公司管理员名称")
    @LogOperation("获取公司管理员名称")
    public Result<SysCompEntity> getAdminUserName(@RequestBody SysCompDTO compDTO) {
        SysCompEntity compNameListById = sysCompService.getCompanyById(compDTO.getId());
        return new Result<SysCompEntity>().ok(compNameListById);
    }
}

